package androidvn.xenforo.fourums;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import androidvn.xenforo.fourums.R;
import androidvn.xenforo.fourums.adapter.CustomThreadListAdapter;
import androidvn.xenforo.fourums.model.Thread;
import androidvn.xenforo.fourums.widget.JsonParser;
import androidvn.xenforo.fourums.widget.PullAndLoadListView;
import androidvn.xenforo.fourums.widget.PullAndLoadListView.OnLoadMoreListener;
import androidvn.xenforo.fourums.widget.PullToRefreshListView.OnRefreshListener;

import android.app.Activity;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

public class ThreadFragment extends ListFragment {
	private int loadMoreThread = 10, index = 0;
	private ProgressDialog pDialog;
	private JsonParser jsonParser = new JsonParser();
	private Thread thread = new Thread();
	private ArrayList<Thread> threadList;
	private ArrayList<Thread> threadListLoad;

	private int groupPosition, childPosition;
	private String forumId;

	// JSON url
	private static final String URL = "http://android.vn/api.php?action=getThreads&order_by=post_date";
	// ALL JSON node names
	private static final String TAG_THREAD_ID = "thread_id";
	private static final String TAG_NODE_ID = "node_id";
	private static final String TAG_USERNAME = "username";
	private static final String TAG_TITLE = "title";
	private static final String TAG_FIRST_POST_ID = "first_post_id";
	private static final String TAG_REPLY_COUNT = "reply_count";
	private static final String TAG_VIEW_COUNT = "view_count";
	private static final String TAG_POST_DATE = "post_date";

	// private static final String TAG_BOX = "nameBox";

	setOnThreadClickListener communicator;

	@Override
	public void onAttach(Activity activity) {

		super.onAttach(activity);
		try {
			communicator = (setOnThreadClickListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement setOnForumClickListener");
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		threadList = new ArrayList<Thread>();
		threadListLoad = new ArrayList<Thread>();
		Bundle bundle = this.getArguments();
		if (bundle != null) {

			forumId = bundle.getString("nodeId");
			groupPosition = bundle.getInt("groupPosition");
			childPosition = bundle.getInt("childPosition");
			Log.d("On Thread Params >>>", "ForumID: " + forumId + " / "
					+ groupPosition + " - " + childPosition + " / Status: "
					+ Global.loginStatus + " - Username: " + Global.userName
					+ " - Hash: " + Global.userHash);
		}
		setRetainInstance(true);
		new LoadData().execute();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.thread_list_layout, container,
				false);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// new LoadData().execute();
		// on thread item click

		getListView().setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Log.d("thread id", threadList.get(position - 1).getThreadId());
				communicator.onThreadClick(threadList.get(position - 1)
						.getThreadId());
			}
		});
		// refresh list view
		((PullAndLoadListView) getListView())
				.setOnRefreshListener(new OnRefreshListener() {
					@Override
					public void onRefresh() {
						new PullRefreshList().execute();
					}
				});
		((PullAndLoadListView) getListView())
				.setOnLoadMoreListener(new OnLoadMoreListener() {
					@Override
					public void onLoadMore() {
						loadMoreThread += 10;
						index = threadList.size();
						new LoadMoreData().execute();
					}
				});
		// ((LoadMoreListView) getListView()).onLoadMoreComplete();
	}

	@Override
	public void onResume() {
		// onResume happens after onStart and onActivityCreated
		super.onResume();
	}

	@Override
	public void onPause() {
		new PullRefreshList().cancel(true);
		new LoadMoreData().cancel(true);
		new LoadData().cancel(true);
		super.onPause();

	}

	// // check status of fragment
	// private boolean isAsyncTaskPendingOrRunning() {
	// return this.asyncTaskWeakRef1 != null
	// && this.asyncTaskWeakRef1.get() != null
	// && !this.asyncTaskWeakRef1.get().getStatus()
	// .equals(Status.FINISHED);
	// }

	class LoadMoreData extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... agrs) {

			if (isCancelled()) {
				return null;
			}
			try {
				java.lang.Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			String limit = String.valueOf(loadMoreThread);
			ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
			if (forumId.toString().trim().length() > 0) {
				params.add(new BasicNameValuePair("node_id", forumId));
			} else {
				switch (groupPosition) {
				case 0:

					break;
				case 1:

					break;
				case 2:
					switch (childPosition) {
					case 1:

						break;
					case 2:

						break;
					default:
						break;
					}

					break;
				case 3:

					break;

				default:

					break;
				}
			}
			params.add(new BasicNameValuePair("limit", limit));
			threadListLoad = new ArrayList<Thread>();

			JSONObject jsonRespond = jsonParser.makeHttpRequest(URL, "GET",
					params);

			if (jsonRespond != null) {
				try {
					JSONObject jsonThreads = jsonRespond
							.getJSONObject("threads");

					Iterator<?> keys = jsonThreads.keys();
					while (keys.hasNext()) {
						String key = (String) keys.next();
						JSONObject jsonThread = jsonThreads.getJSONObject(key);

						thread = new Thread();
						thread.setThreadId(jsonThread.getString(TAG_THREAD_ID));
						thread.setNodeId(jsonThread.getString(TAG_NODE_ID));
						thread.setUserName(jsonThread.getString(TAG_USERNAME));
						thread.setTitle(jsonThread.getString(TAG_TITLE));
						thread.setPostDate(jsonThread
								.getString(TAG_FIRST_POST_ID));
						thread.setViewCount(jsonThread
								.getString(TAG_VIEW_COUNT));
						thread.setReplyCount(jsonThread
								.getString(TAG_REPLY_COUNT));
						//
						thread.setPostDate(DateFormat.getDateInstance().format(
								new Date(Long.valueOf(jsonThread
										.getString(TAG_POST_DATE) + "000"))));
						threadListLoad.add(thread);
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			if (threadList.size() < threadListLoad.size()) {
				for (int i = index; i < threadListLoad.size(); i++) {
					Thread thread = threadListLoad.get(i);
					threadList.add(thread);
				}
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {

			((CustomThreadListAdapter) getListAdapter()).notifyDataSetChanged();

			super.onPostExecute(result);
		}

		// @Override
		// protected void onCancelled() {
		// ((LoadMoreListView) getListView()).onLoadMoreComplete();
		// super.onCancelled();
		// }
	}

	// refresh list view
	class PullRefreshList extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... args) {
			if (isCancelled()) {
				return null;
			}
			try {
				java.lang.Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			threadList.clear();

			// add new list thread
			ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
			if (forumId.trim().length() > 0) {
				params.add(new BasicNameValuePair("node_id", forumId));
			} else {
				switch (groupPosition) {
				case 0:

					break;
				case 1:

					break;
				case 2:
					switch (childPosition) {
					case 1:

						break;
					case 2:

						break;
					default:
						break;
					}

					break;
				case 3:

					break;

				default:

					break;
				}
			}

			JSONObject jsonRespond = jsonParser.makeHttpRequest(URL, "GET",
					params);
			if (jsonRespond != null) {
				try {
					JSONObject jsonThreads = jsonRespond
							.getJSONObject("threads");

					Iterator<?> keys = jsonThreads.keys();
					while (keys.hasNext()) {
						String key = (String) keys.next();
						JSONObject jsonThread = jsonThreads.getJSONObject(key);

						thread = new Thread();
						thread.setThreadId(jsonThread.getString(TAG_THREAD_ID));
						thread.setNodeId(jsonThread.getString(TAG_NODE_ID));
						thread.setUserName(jsonThread.getString(TAG_USERNAME));
						thread.setTitle(jsonThread.getString(TAG_TITLE));
						//
						thread.setPostDate(DateFormat.getDateInstance().format(
								new Date(Long.valueOf(jsonThread
										.getString(TAG_POST_DATE) + "000"))));
						//
						thread.setViewCount(jsonThread
								.getString(TAG_VIEW_COUNT));
						thread.setReplyCount(jsonThread
								.getString(TAG_REPLY_COUNT));

						threadList.add(thread);
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			// Function.CollectionSortDESC(threadList, "post_date");

			loadMoreThread = 10;
			index = 10;
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			((CustomThreadListAdapter) getListAdapter()).notifyDataSetChanged();
			((PullAndLoadListView) getListView()).onRefreshComplete();
		}

		// @Override
		// protected void onCancelled() {
		// ((PullAndLoadListView) getListView()).onRefreshComplete();
		// super.onCancelled();
		// }

	}

	class LoadData extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {

			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Loading ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... args) {
			if (isCancelled()) {
				return null;
			}
			try {
				java.lang.Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			threadList.clear();

			ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
			// filter parameters
			if (forumId.trim().length() > 0) {
				params.add(new BasicNameValuePair("node_id", forumId));
			} else {
				switch (groupPosition) {
				case 0:

					break;
				case 1:

					break;
				case 2:
					switch (childPosition) {
					case 1:

						break;
					case 2:

						break;
					default:
						break;
					}

					break;
				case 3:

					break;

				default:

					break;
				}
			}

			JSONObject jsonRespond = jsonParser.makeHttpRequest(URL, "GET",
					params);
			// Log.d("JSON RESPOND >>>", jsonRespond.toString());
			if (jsonRespond != null) {
				try {
					JSONObject jsonThreads = jsonRespond
							.getJSONObject("threads");

					Iterator<?> keys = jsonThreads.keys();
					while (keys.hasNext()) {
						String key = (String) keys.next();
						JSONObject jsonThread = jsonThreads.getJSONObject(key);

						thread = new Thread();
						thread.setThreadId(jsonThread.getString(TAG_THREAD_ID));
						thread.setNodeId(jsonThread.getString(TAG_NODE_ID));
						thread.setUserName(jsonThread.getString(TAG_USERNAME));
						thread.setTitle(jsonThread.getString(TAG_TITLE));
						thread.setPostDate(jsonThread
								.getString(TAG_FIRST_POST_ID));
						thread.setViewCount(jsonThread
								.getString(TAG_VIEW_COUNT));
						thread.setReplyCount(jsonThread
								.getString(TAG_REPLY_COUNT));
						//
						thread.setPostDate(DateFormat.getDateInstance().format(
								new Date(Long.valueOf(jsonThread
										.getString(TAG_POST_DATE) + "000"))));
						//
						threadList.add(thread);

						/*
						 * getListView().setOnItemClickListener(new
						 * OnItemClickListener() {
						 * 
						 * @Override public void onItemClick(AdapterView<?>
						 * arg0, View arg1, int position, long arg3) {
						 * Log.d("thread id",
						 * threadList.get(position).getThreadId());
						 * communicator.onThreadClick(threadList.get(position)
						 * .getThreadId()); } });
						 */
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					CustomThreadListAdapter adapter = new CustomThreadListAdapter(
							getActivity(), threadList);
					setListAdapter(adapter);
				}
			});

			pDialog.dismiss();

		}
	}

	public void setCommunicator(setOnThreadClickListener communicator) {
		this.communicator = communicator;
	}

	interface setOnThreadClickListener {
		public void onThreadClick(String threadId);

	}

	public void getThreadId(String nodeId) {
		this.forumId = nodeId;
	}
}
